﻿@page "/publish/course/{CourseId:int}/chapters/{ChapterId:int}/resources"
@using AntDesign.TableModels
@inject NavigationManager Nav
@inject MessageService Message

<!-- 章节资源管理界面 -->
<AntDesign.PageHeader Title="资源管理"
OnBack="@(() => Nav.NavigateTo($"/publish/course/{CourseId}"))">
</AntDesign.PageHeader>

<!-- 资源表格 -->
<Table TItem="Resource"
DataSource="_dataSource"
Total="_total"
PageSize="5"
@ref="_table"
OnChange="OnTableChange"
Bordered
Size="TableSize.Middle">
    <TitleTemplate>
        <Flex Justify="FlexJustify.SpaceBetween">
            <Space>
                <Button Type="ButtonType.Primary" OnClick="ShowCreateModal">
                    <Icon Type="plus" /> 新增资源
                </Button>
                <Button Danger
                Disabled="!_selectedResource.Any()"
                OnClick="DeleteSelected">
                    批量删除
                </Button>
            </Space>
        </Flex>
    </TitleTemplate>
    <ColumnDefinitions Context="resource">
        <PropertyColumn Title="资源类型" Property="@(r => r.Type)" />
        <PropertyColumn Title="排序" Property="@(r => r.ResourceOrder)" Sortable />

        <ActionColumn Title="操作" Width="150px">
            <Button Type="ButtonType.Link" OnClick="@(() => StartEdit(resource))">编辑</Button>
            <Button Type="ButtonType.Link" OnClick="@(() => DeleteResource(resource))">删除</Button>
        </ActionColumn>
    </ColumnDefinitions>
</Table>
<Divider Orientation="DividerOrientation.Left" Plain>
    Editing Place Here ⬇
</Divider>
<!-- 动态编辑区域 -->
@if (_editingResource != null)
{

    @if (_editingResource.Type == "Markdown")
    {
        <MarkdownEditor
        @ref="Markdown1"
        @bind-Value="_markdownContent"
        SpellChecker="false"
        ValueHTMLChanged="@OnMarkdownValueHTMLChanged" />

        <Button Type="ButtonType.Primary" OnClick="SaveMarkdown">保存内容</Button>
        <Divider Orientation="DividerOrientation.Left" Plain>
            Result Here ⬇
        </Divider>
        @((MarkupString)markdownHtml)
    }
    else if (_editingResource.Type == "Video")
    {
        <Upload Action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        Name="files"
        OnSingleCompleted="OnSingleCompleted">
            <Button Icon="upload">
                <span>上传视频</span>
            </Button>
        </Upload>

    }
}
<Modal @bind-Visible="modalVisible"
Title="@("新增资源")"
OnOk="SubmitForm">
    <Form Model="@ResourceTobeCreated">
        <FormItem Label="类别"
        Rules="@(new[] { new FormValidationRule { Required = true } })">
            <Input @bind-Value="ResourceTobeCreated.Type" />
        </FormItem>
        <FormItem Label="排序序号"
        Rules="@(new[] { new FormValidationRule { Type = FormFieldType.Number } })">
            <Input @bind-Value="ResourceTobeCreated.ResourceOrder" />
        </FormItem>
    </Form>
</Modal>




@code {
    [Parameter] public int CourseId { get; set; }
    [Parameter] public int ChapterId { get; set; }

    private ITable _table;
    private MarkdownEditor Markdown1;
    private List<Resource> _allResources = new();
    private List<Resource> _dataSource = new();
    private IEnumerable<Resource> _selectedResource = new List<Resource>();

    private int _total;
    private bool modalVisible;
    private Resource ResourceTobeCreated;
    private Resource _editingResource;
    private string _markdownContent = "";
    private string markdownHtml = string.Empty;


    protected override async Task OnInitializedAsync()
    {
        markdownHtml = Markdig.Markdown.ToHtml(_markdownContent ?? string.Empty);
        await LoadData();
        await base.OnInitializedAsync();

    }

    private void OnTableChange(QueryModel<Resource> query)
    {
        var queryable = _allResources.AsQueryable();
        _dataSource = queryable.ExecuteTableQuery(query)
                              .CurrentPagedRecords(query)
                              .ToList();
    }

    private Task OnMarkdownValueHTMLChanged(string value)
    {
        markdownHtml = value;
        return Task.CompletedTask; 
    }

    private async Task LoadData()
    {
        //_allResources = await ResourceService.GetResourcesByChapter(ChapterId);
        _allResources = new List<Resource>()
        {
            new Resource
            {
                Id = 1,
                ChapterId = 1,
                ResourceOrder = 1,
                Type = "Markdown"

            },
            new Resource
            {
                Id = 2,
                ChapterId = 1,
                ResourceOrder = 2,
                Type = "Video"
            }
        };
        await Task.Delay(10);
        _total = _allResources.Count;
        _table.ReloadData();
    }



    private void StartEdit(Resource resource)
    {
        _editingResource = resource;
        if (resource.Type == "Markdown")
        {
            // 这里需要真实服务获取Markdown内容
            _markdownContent = "从ResourceService获取的Markdown内容";
        }
    }

    private async Task SaveMarkdown()
    {
        // 调用Markdown资源更新服务
        // await ResourceService.UpdateMarkdown(new MarkdownResource{
        //     ResourceId = _editingResource.Id,
        //     Content = _markdownContent
        // });
        await LoadData();
        await Message.Success("内容保存成功");
        markdownHtml = Markdig.Markdown.ToHtml(_markdownContent ?? string.Empty);
    }


    private async Task OnSingleCompleted(UploadInfo fileinfo)
    {
        if (fileinfo.File.State == UploadState.Success)
        {
            var result = fileinfo.File.GetResponse<VideoResource>();
            fileinfo.File.Url = result.VideoUrl;
            await Message.Success("视频上传成功");
            await LoadData();
        }
    }

    private void ShowCreateModal()
    {
        ResourceTobeCreated = new()
            {
                ChapterId = ChapterId
            };
        modalVisible = true;
    }

    private async Task SubmitForm()
    {
        //await ResourceService.AddNewResourceAsync(currentChapter)
        modalVisible = false;
        await LoadData();
        await Message.Success("新增成功");
    }

    private async Task DeleteSelected()
    {
        //await ChapterService.DeleteChaptersAsync(_selectedChapters.Select(c => c.Id));
        await LoadData();
    }

    private async Task DeleteResource(Resource resource)
    {
        //await ResourceService.DeleteResourceAsync(chapter.Id);
        await LoadData();
        await Message.Success("删除成功");
    }
}